package com.yjk.mall.product.service.impl;

import com.yjk.mall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjk.common.utils.PageUtils;
import com.yjk.common.utils.Query;

import com.yjk.mall.product.dao.CategoryDao;
import com.yjk.mall.product.entity.CategoryEntity;
import com.yjk.mall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> listAll=baseMapper.selectList(null);
        List<CategoryEntity> collect = listAll.stream()
                .filter(entity -> entity.getParentCid() == 0)
                .map(entity->{entity.setChildren(getChild(entity,listAll));return entity;})
                .collect(Collectors.toList());
        return collect;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        baseMapper.deleteBatchIds(asList);
    }

    @Transactional
    @Override
    public void updateRelById(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    public List<CategoryEntity> getChild(CategoryEntity entity,List<CategoryEntity> listAll){
        List<CategoryEntity> children=listAll.stream()
                .filter(current->current.getParentCid()==entity.getCatId())
                .map(current->{
                    current.setChildren(getChild(current,listAll));
                    return current;
                })
                .collect(Collectors.toList());
        return children;
    }
}